/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Util;

import Controller.SenhaBean;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.codehaus.jettison.json.JSONException;
import org.primefaces.context.RequestContext;

/**
 *
 * @author pedro
 */
public class senhaUtil {
    
     public static String urlServer=ConfUtil.url;

    public  static  void recuperaSenha(SenhaBean email) throws JSONException {

        Gson gson = new Gson();
            
       
        try {
            RequestContext context = RequestContext.getCurrentInstance();
            FacesMessage msg = null;
            boolean loggedIn = false;

            URL url = new URL(urlServer+"enviaSenha");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");

           

            String json = gson.toJson(email);

          System.out.println(json);

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes());
            os.flush();

            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                if(output.equals("Fail")){
                   loggedIn =false;
                   msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atenção", "O email informado não existe em nossa base de usuários");
                }
                if(output.equals("OK")){
                   loggedIn =true;
                   msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Informação", "Senha enviada com sucesso");
                }
               FacesContext.getCurrentInstance().addMessage(null, msg);
               context.addCallbackParam("loggedIn", loggedIn);
            }
           

            conn.disconnect();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }
    }
    
}
